<?php
hd_core::load_class('init', 'admin');
class admin_order_control extends init_control {

	public function _initialize() {
		parent::_initialize();
		/* 服务层 */
		$this->service = $this->load->service('order/order');
		$this->service_order_log = $this->load->service('order/order_log');
		$this->service_initiate = $this->load->service('school/initiate');
	}

	/* 订单列表管理 */
	public function index() {
		// 查询条件
		$sqlmap = array();
		$sqlmap = $this->service->build_sqlmap($_GET);
		if(isset($_GET['daochu'])){
			$this->daochu($sqlmap);
			echo "111";die();
		}
		$limit = (isset($_GET['limit']) && is_numeric($_GET['limit'])) ? $_GET['limit'] : 20;
		$orders = $this->service->get_order_lists($sqlmap,$_GET['page'],$limit);
		$count  = $this->service->count($sqlmap);
		$pages  = $this->admin_pages($count, $limit);
		$lists = array(
			'th' => array(
				'sn' => array('title' => '订单号','length' => 15),
				'username' => array('title' => '家长姓名','length' => 10),
				'student_name' => array('length' => 10,'title' => '孩子名称'),
				'school_name' => array('title' => '学校名称','length' => 15),
				'system_time' => array('length' => 12,'title' => '下单时间','style'=>'date'),
				'real_amount' => array('length' => 8,'title' => '订单金额'),
				'_pay_type' => array('length' => 8,'title' => '支付方式'),
				'payType' => array('length' => 8,'title' => '缴费类型','style' => 'payType'),
				'_status' => array('length' => 8,'title' => '订单状态','style'=>'_status')
			),
			'lists' => $orders,
			'pages' => $pages,
		);
		$this->load->librarys('View')->assign('lists',$lists)->assign('pages',$pages)->display('index');
	}
	
	/* 订单列表管理 */
	public function initiate() {
		// 查询条件
		$sqlmap = array();
		$sqlmap = $this->service_initiate->build_sqlmap($_GET);
		$limit = (isset($_GET['limit']) && is_numeric($_GET['limit'])) ? $_GET['limit'] : 20;
		$orders = $this->service_initiate->get_lists($sqlmap,$_GET['page'],$limit);
		$count  = $this->service_initiate->count($sqlmap);
		$pages  = $this->admin_pages($count, $limit);
		$lists = array(
			'th' => array(
				//'initiate_name' => array('title' => '发起人','length' => 10),
				'school_name' => array('title' => '发起学校','length' => 20),
				'number' => array('length' => 10,'title' => '开班人数'),
				'initiate_number' => array('title' => '已有人数','length' => 10),
				'area' => array('length' => 8,'title' => '所在区域'),
				'addtime' => array('length' => 12,'title' => '申请时间','style'=>'date'),
				'_open' => array('length' => 7,'title' => '开班状态','style'=>'_open'),
				'_status' => array('length' => 8,'title' => '状态','style'=>'_status')
			),
			'lists' => $orders,
			'pages' => $pages,
		);
		$this->load->librarys('View')->assign('lists',$lists)->assign('pages',$pages)->display('initiate');
	}
	
	public function edit(){
		$info = $this->service_initiate->get_initiate_by_id($_GET['id']);
		if(checksubmit('dosubmit')) {
			$result = $this->service_initiate->edit_initiate($_GET);
			if($result === FALSE){
				showmessage($this->service_initiate->error);
			}else{
				showmessage(lang('_operation_success_'),url('initiate'));
			}
		}else{
			$this->load->librarys('View')->assign('info',$info)->display('initiate_edit');
		}
	}
	/* 订单详细页面 */
	public function detail() {
		$order = $this->service->find(array('sn' => $_GET['sn']));
		if (!$order) showmessage(lang('order_not_exist','order/language'));
		
		// 日志
		$order_logs = $this->service_order_log->get_by_order_sn($order['sn'],'id DESC');
		$this->load->librarys('View')->assign('order',$order)->assign('order_logs',$order_logs)->assign('status',$status)->display('detail');
	}

	/* 确认付款 */
	public function pay() {
		if (checksubmit('dosubmit')) {
			$params = array();
			$params['pay_status'] = remove_xss(strtotime($_GET['pay_status']));
			$params['paid_amount']= sprintf("%0.2f", (float) $_GET['paid_amount']);
			$params['pay_method'] = remove_xss($_GET['pay_method']);
			$params['pay_sn']     = remove_xss($_GET['pay_sn']);
			$params['msg']        = remove_xss($_GET['msg']);
			if ($params['pay_method'] != 'other' && !$params['pay_sn']) {
				showmessage(lang('pay_deal_sn_empty','order/language'));
			}
			$result = $this->service->set_order($_GET['order_sn'] ,'pay' ,'',$params);
			if (!$result) showmessage($this->service_sub->error);
			showmessage(lang('pay_success','order/language'),'',1,'json');
		} else {
			// 获取所有已开启的支付方式
			$pays = model('pay/payment','service')->get();
			foreach ($pays as $k => $pay) {
				$pays[$k] = $pay['pay_name'];
			}
			$pays['other'] = '其它付款方式';
			$order = $this->service->find(array('sn' => $_GET['order_sn']));
			$this->load->librarys('View')->assign('pays',$pays)->assign('order',$order)->display('alert_pay');
		}
	}

	/* 确认完成 */
	public function finish() {
		if (checksubmit('dosubmit')) {
			$result = $this->service->set_order($_GET['order_sn'] ,'finish' ,'',array('msg'=>$_GET['msg']));
			if (!$result) showmessage($this->service->error);
			showmessage(lang('确认完成成功'),'',1,'json');
		} else {
			$this->load->librarys('View')->display('alert_finish');
		}
	}

	/* 取消订单 */
	public function cancel() {
		if (checksubmit('dosubmit')) {
			$order_sn = $_GET['order_sn'];
			$this->load->service('order/order_trade')->setField(array('status'=>-1), array('order_sn'=>$order_sn));

			$result = $this->service->set_order($order_sn ,'order' ,2,array('msg'=>$_GET['msg'],'isrefund' => 1));
			if (!$result) showmessage($this->service->error,'',0,'json');
			showmessage(lang('cancel_order_success','order/language'),'',1,'json');
		} else {
			$order = $this->service->find(array('sn' => $_GET['order_sn']));
			$this->load->librarys('View')->assign('order',$order)->display('alert_cancel');
		}
	}

	/* 作废 */
	public function recycle() {
		if (checksubmit('dosubmit')) {
			$result = $this->service->set_order($_GET['order_sn'] ,'order' ,3,array('msg'=>$_GET['msg']));
			if (!$result) showmessage($this->service->error);
			showmessage(lang('cancellation_order_success','order/language'),'',1,'json');
		} else {
			$this->load->librarys('View')->display('alert_recycle');
		}
	}

	/* 删除订单 */
	public function delete() {
		if (checksubmit('dosubmit')) {
			$result = $this->service->set_order($_GET['service'] ,'order' ,4);
			if (!$result) showmessage($this->service->error);
			showmessage(lang('删除订单成功'),url('order/admin_order/index'),1,'json');
		} else {
			showmessage(lang('_error_action_'));
		}
	}

	/* 修改订单应付总额 */
	public function update_real_price() {
		if (checksubmit('dosubmit')) {
			$result = $this->service->update_real_price($_GET['sn'] ,$_GET['real_amount']);
			if (!$result) {
				showmessage($this->service->error);
			}
			showmessage(lang('修改订单应付总额成功'),'',1,'json');
		} else {
			$order = $this->service->find(array('sn' => $_GET['sn']));
			$this->load->librarys('View')->assign('order',$order)->display('alert_update_real_price');
		}
	}
	
	public function classes(){
		if (checksubmit('dosubmit')) {
			$ids = remove_xss($_GET['ids']);
			$school_id = intval($_GET['school_id']);
			$class_id = intval($_GET['class_id']);
			$iid = intval($_GET['iid']);
			if ($class_id==0) showmessage("请选择班级");
			$data['school_id'] = $school_id;
			$data['school_name'] = $this->load->table('school/school')->where(array('id'=>$school_id))->getField('name');
			$data['class_id'] = $class_id;
			//$data['class_name'] = $this->load->table('school/class')->where(array('id'=>$class_id))->getField('name');
			$result = $this->load->table('member/member_student')->where(array('id'=>array("IN",$ids)))->save($data);
			if (!$result) showmessage("分配班级失败");
			
			$this->load->table('school/initiate')->where(array('id'=>$iid))->save(array('isopen'=>1));
			showmessage(lang('分配班级成功'),'',1,'json');
		}else{
			$iid = intval($_GET['iid']);
			$initiate = $this->load->table('school/initiate')->where(array('id'=>$iid))->find();
			$class = $this->load->service('school/class')->get_lists(1,1000,array('school_id'=>$initiate['school_id']));
			$school = $this->load->table('school/school')->where(array('id'=>$initiate['school_id']))->find();
			foreach ($class as $k => $v) {
				$clists[$v['id']] = $v['name']."(".$school['name'].")";
			}
			if(!$clists){
				$clists[0] = "请先添加班级(".$school['name'].")";
			}
			$this->load->librarys('View')->assign('ids',$_GET['ids'])->assign('iid',$_GET['iid'])->assign('clists',$clists)->assign('school_id',$initiate['school_id'])->display('alert_classes');
		}
	}
	
	public function kb(){
		$iid = intval($_GET['iid']);
		$info = $this->service_initiate->get_initiate_by_id($iid);
		if($info){
			$this->load->table('school/initiate')->where(array('id'=>$iid))->save(array('isopen'=>1));
			showmessage('_operation_success_',url('initiate'),1);
		}else{
			showmessage("发起托班数据不存在");
		}
	}
	
	public function tk(){
		$iid = intval($_GET['iid']);
		$info = $this->service_initiate->get_initiate_by_id($iid);
		if($info && $info['isopen'] == 0 && $info['status'] == 1){
			$orders = $this->load->table('order/order')->where(array('pay_status'=>1,'finish_status'=>0,'status'=>1))->select();
			foreach($orders as $k => $v){
				$money = $v['real_amount'];			
				$field = "money";
				$msg = "托班申请因人数未达标开班失败，退款";
				$mid = $v['buyer_id'];
				$this->load->table('member')->where(array('id' => $mid))->setField($field, array("exp", $field.$money));
				$_member = $this->load->table('member')->setid($mid)->output();
				$log_info = array(
					'mid'      => $mid,
					'value'    => $money,
					'ltype'     => 1,
					'type'     => $field,
					'msg'      => $msg,
					'dateline' => TIMESTAMP,
					'admin_id' => (defined('IN_ADMIN')) ? ADMIN_ID : 0,
					'money_detail' => json_encode(array($field => sprintf('%.2f' ,$_member[$field])))
				);
				$this->service->set_order($v['sn'] ,'order' ,2,array('msg'=>'托班申请因人数未达标开班失败，取消订单','isrefund' => 0));
				$this->load->table('school/initiate')->where(array('id'=>$iid))->save(array('status'=>0));
				$this->load->table('member_log')->update($log_info);			
			}
			showmessage('_operation_success_',url('initiate'),1);
		}else{
			showmessage("发起托班数据不存在");
		}
	}
	
	public function daochu($sqlmap){
		$orders = $this->service->get_order_lists($sqlmap);
		require_once APP_PATH.'library/Classes/PHPExcel.php'; 
		require_once APP_PATH.'library/Classes/PHPExcel/Writer/Excel2007.php'; 
		require_once APP_PATH.'library/Classes/PHPExcel/Writer/Excel5.php'; 
		include_once APP_PATH.'library/Classes/PHPExcel/IOFactory.php'; 
		$objExcel = new PHPExcel(); 
		//设置属性 (这段代码无关紧要，其中的内容可以替换为你需要的) 
		$objExcel->getProperties()->setCreator("andy"); 
		$objExcel->getProperties()->setLastModifiedBy("andy"); 
		$objExcel->getProperties()->setTitle("Office 2003 XLS Test Document"); 
		$objExcel->getProperties()->setSubject("Office 2003 XLS Test Document"); 
		$objExcel->getProperties()->setDescription("Test document for Office 2003 XLS, generated using PHP classes."); 
		$objExcel->getProperties()->setKeywords("office 2003 openxml php"); 
		$objExcel->getProperties()->setCategory("Test result file"); 
		$objExcel->setActiveSheetIndex(0); 
		$i=0; 
		
		
			
		//表头 
		$k1="订单号"; 
		$k2="家长姓名"; 
		$k3="孩子名称"; 
		$k4="学校名称"; 
		$k5="下单时间"; 
		$k6="订单金额";
		$k7="支付方式";
		$k8="缴费类型";
		$k9="订单状态";
		$objExcel->getActiveSheet()->setCellValue('a1', "$k1"); 
		$objExcel->getActiveSheet()->setCellValue('b1', "$k2"); 
		$objExcel->getActiveSheet()->setCellValue('c1', "$k3"); 
		$objExcel->getActiveSheet()->setCellValue('d1', "$k4"); 
		$objExcel->getActiveSheet()->setCellValue('e1', "$k5");
		$objExcel->getActiveSheet()->setCellValue('f1', "$k5"); 
		$objExcel->getActiveSheet()->setCellValue('g1', "$k7"); 
		$objExcel->getActiveSheet()->setCellValue('h1', "$k8"); 
		$objExcel->getActiveSheet()->setCellValue('i1', "$k9"); 
		//debug($links_list); 
		foreach($orders as $k=>$v) { 
		  $u1=$i+2; 
		  /*----------写入内容-------------*/			
		  $objExcel->getActiveSheet()->setCellValue('a'.$u1, (string)$v["sn"]." "); 
		  $objExcel->getActiveSheet()->setCellValue('b'.$u1, $v["username"]); 
		  $objExcel->getActiveSheet()->setCellValue('c'.$u1, $v["student_name"]); 
		  $objExcel->getActiveSheet()->setCellValue('d'.$u1, $v["school_name"]); 
		  $objExcel->getActiveSheet()->setCellValue('e'.$u1, date("Y-m-d H:i:s",$v["system_time"])); 
		  $objExcel->getActiveSheet()->setCellValue('f'.$u1, $v["real_amount"]); 
		  $objExcel->getActiveSheet()->setCellValue('g'.$u1, $v["_pay_type"]); 
		  $objExcel->getActiveSheet()->setCellValue('h'.$u1, ch_payType($v["payType"])); 
		  $objExcel->getActiveSheet()->setCellValue('i'.$u1, ch_status($v["_status"])); 
		  $i++; 
		} 
		// 高置列的宽度 
		$objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10); 
		$objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(10); 
		$objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(70); 
		$objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15); 
		$objExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15); 
		$objExcel->getActiveSheet()->getHeaderFooter()->setOddHeader('&L&BPersonal cash register&RPrinted on &D'); 
		$objExcel->getActiveSheet()->getHeaderFooter()->setOddFooter('&L&B' . $objExcel->getProperties()->getTitle() . '&RPage &P of &N'); 
		// 设置页方向和规模 
		$objExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT); 
		$objExcel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4); 
		$objExcel->setActiveSheetIndex(0); 
		$timestamp = time(); 
		if($ex == '2007') { //导出excel2007文档 
		  header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 
		  header('Content-Disposition: attachment;filename="订单记录'.date("Y-m-d",$timestamp).'.xlsx"'); 
		  header('Cache-Control: max-age=0'); 
		  $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007'); 
		  $objWriter->save('php://output'); 
		  exit; 
		} else { //导出excel2003文档 
		  header('Content-Type: application/vnd.ms-excel'); 
		  header('Content-Disposition: attachment;filename="订单记录'.date("Y-m-d",$timestamp).'.xls"'); 
		  header('Cache-Control: max-age=0'); 
		  $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5'); 
		  $objWriter->save('php://output'); 
		  exit; 
		}	
	}
}